from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from settings import Config
from itsdangerous import BadData
from flask import g


def login_token(user_id):

    # 1.创建序列化器
    s = Serializer(secret_key=Config.SECRET_KEY, expires_in=Config.JWT_EXPIRES_IN)

    # 2.加密数据
    token = s.dumps({
        'user_id': user_id
    })

    # 3.返回token
    return token.decode()


def check_user_token(token):

    # 1.创建序列化器
    s = Serializer(secret_key=Config.SECRET_KEY, expires_in=Config.JWT_EXPIRES_IN)

    # 2.验证数据
    try:
        data = s.loads(token)
    except BadData:
        return None
    # 3.返回数据
    return data.get('user_id')


def loginrequired(func):

    def wrapper(*args, **kwargs):
        if g.user_id:
            return func(*args, **kwargs)
        else:
            return {'msg': '请登录'}

    return wrapper
